package com.heima.article.listener;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.heima.article.entity.ApArticle;
import com.heima.article.service.IApArticleService;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Service;

import javax.security.auth.login.Configuration;

/**
 * kafka 监听消息, 接收消息
 */
@Service
public class UpDownListener {

    @Autowired
    IApArticleService articleService; // 文章信息表


    // 指定监听主题名称
    @KafkaListener(topics = "${topic.upDownTopic}")
    public void handleMsg(ConsumerRecord<String, String> record){
        //1. 接收到消息 作者id
        String key = record.key();
        //从key中解析文章作者id, 将字符串转换成long
        long articleId = Long.parseLong(key);
        //2. 接收值value 获取当前状态
        String value = record.value();
        //2.1 如果是 1上架: 发一个0上架, 否则发1下架
        Integer isDown = value.equals("1") ? 0 : 1;
        System.out.println("接收到的上下架消息: articleId = " + articleId + ", isDown = " + isDown);
        //3. 构建修改条件
        LambdaUpdateWrapper<ApArticle> update = new LambdaUpdateWrapper<>();
        //4. 根据文章作者id 修改
        update.eq(ApArticle::getId, articleId);
        //5. 把 上下架状态传进去进行修改
        update.set(ApArticle::getIsDown, isDown);
        //6. 调用文章信息表服务更新文章状态
        articleService.update(update);
    }
}
